package dao.impl;

import dao.BaseDao;
import dao.MemoDao;
import entity.Memo;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class MemoDaoImpl extends BaseDao implements MemoDao {
    Connection conn;
    PreparedStatement pstmt;
    ResultSet rs;
    @Override
    public int selectMemoCount(int uid) {
        int r = 0;
        conn = getConnection();
        String sql = "select count(*) from memo where uid = ?";
        try {
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1,uid);
            rs = pstmt.executeQuery();
            while (rs.next()){
                r = rs.getInt(1);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return r;
    }

    @Override
    public List<Memo> selectMemos(int mtid) {
        List<Memo> memos = new ArrayList<>();
        conn = getConnection();
        String sql = "select * from memo";
        if (mtid != 0){
            sql = "select * from memo where mtid = "+mtid;
        }
        try {
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            while (rs.next()){
                int mid = rs.getInt("mid");
                mtid = rs.getInt("mtid");
                int uid = rs.getInt("uid");
                String mtitle = rs.getString("mtitle");
                String memo = rs.getString("memo");
                String mcreateTime = rs.getString("mcreateTime");
                Memo m = new Memo(mid,mtid,uid,mtitle,memo,mcreateTime);
                memos.add(m);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return memos;
    }

    @Override
    public Memo selectMemo(int mid) {
        Memo m = new Memo();
        conn = getConnection();
        String sql = "select * from memo where mid = ?";
        try {
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1,mid);
            rs = pstmt.executeQuery();
            while (rs.next()){
                mid = rs.getInt("mid");
                int mtid = rs.getInt("mtid");
                int uid = rs.getInt("uid");
                String mtitle = rs.getString("mtitle");
                String memo = rs.getString("memo");
                String mcreateTime = rs.getString("mcreateTime");
                m = new Memo(mid,mtid,uid,mtitle,memo,mcreateTime);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return m;
    }
}
